package com.ziroom.zifamily.zfcensor.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>TODO</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2018年11月30日 16:36
 * @since 1.0
 */
@Slf4j
@Component
public class ZkClient {

    @Autowired
    private CuratorFramework client;

    /**
     * 创建父节点，创建成功或存在都返回成功
     * @param path
     * @return
     */
    public boolean createParent(String path) {
        try {
            client.create().creatingParentsIfNeeded().forPath(path);
            return true;
        } catch (KeeperException.NodeExistsException e) {
            return true;
        } catch (Exception e) {
            log.error("createParent fail path:{}", path, e);
        }
        return false;
    }

    /**
     * 创建不存在的节点。如果存在或创建失败，返回false
     * @param path
     * @throws Exception
     */
    public boolean createNotExistEphemeralNode(String path) {
        try {
            client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
            return true;
        } catch (KeeperException.NodeExistsException e) {
            return false;
        }  catch (Exception e) {
            log.error("createNotExistNode fail path:{}", path, e);
        }
        return false;
    }
}
